package com.originskyseed.platform.count.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.count.i18n.CountResponseMsg;
import com.originskyseed.platform.count.model.FinancialManage;
import com.originskyseed.platform.count.model.FinancialManageRelateAnnex;
import com.originskyseed.platform.count.service.IFinancialManageRelateAnnexService;
import com.originskyseed.platform.count.service.IFinancialManageService;
import com.originskyseed.platform.count.vo.request.FinancialManageRequestVO;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * 财务管理信息Controller类（OSI_FINANCIAL_MANAGE）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/financialManage")
@BaseLocaleResource(localeFileName = "i18n_count")
public class FinancialManageController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FinancialManageController.class);

	@DubboReference
	private IFinancialManageService financialManageService;

	@DubboReference
	private IFinancialManageRelateAnnexService financialManageRelateAnnexService;

	/**
	 * KPI分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/financialManageList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<FinancialManage>> financialManageList(HttpServletRequest request) {
		BaseResponseBody<BasePage<FinancialManage>> result = null;
		try {
			// 请求对象
			FinancialManageRequestVO requestVO = this.getParameterBean(FinancialManageRequestVO.class);
			SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM");
			if (StringUtils.isNotBlank(requestVO.getStartTime())) {
				Date end = getLastDayOfMonth(ft.parse(requestVO.getStartTime()));
				requestVO.setEndTime(ft.format(end));
			}
			// 分页查询
			BasePage<FinancialManage> page = new BasePage<FinancialManage>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.financialManageService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<FinancialManage>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.FINANCIAL_MANAGE_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<FinancialManage>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.FINANCIAL_MANAGE_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 开放平台_财务列表_分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/financialList.json")
	@RequiredParams(names = { "pageNo", "pageSize", "type", "feeType"})
	public BaseResponseBody<BasePage<FinancialManage>> financialList(HttpServletRequest request) {
		BaseResponseBody<BasePage<FinancialManage>> result = null;
		try {
			// 请求对象
			FinancialManageRequestVO requestVO = this.getParameterBean(FinancialManageRequestVO.class);
			// UserInfo userInfo = this.getCurrentUserInfo(request,UserInfo.class);
			if (requestVO.getType() != null) {
				// 分页查询
				SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM");
				if (requestVO.getStartTime() != null&&StringUtils.isNotBlank(requestVO.getStartTime())) {
					Date end = getLastDayOfMonth(ft.parse(requestVO.getStartTime()));
					requestVO.setEndTime(ft.format(end));
				}
				BasePage<FinancialManage> page = new BasePage<FinancialManage>(requestVO.getPageNo(), requestVO.getPageSize());
				page = this.financialManageService.financialListByPage(requestVO.toMap(), page);
				result = new BaseResponseBody<BasePage<FinancialManage>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.FINANCIAL_MANAGE_LIST_SUCCESS.getMsg()), page);
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<FinancialManage>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.FINANCIAL_MANAGE_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 开放平台_财务列表 导出Excel
	 *
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/financialToExcel.json")
	@SysLog(module = "财务信息模块", operationDesc = "财务账单信息导出excel")
	public void financialToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<FinancialManage> list = new ArrayList<>();
			FinancialManageRequestVO requestVO = this.getParameterBean(FinancialManageRequestVO.class);
			SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
			if (requestVO.getStartTime() != null) {
				Date end = getLastDayOfMonth(ft.parse(requestVO.getStartTime()));
				requestVO.setEndTime(ft.format(end));
			}
			// UserInfo userInfo = this.getCurrentUserInfo(request,UserInfo.class);
			if (requestVO.getType() != null && requestVO.getType() == 1) {
				list = this.financialManageService.financialListToExcel(requestVO.toMap());
			}
			// excel标题
			String[] title = { "编码", "所属平台", "账号信息", "账单名称", "账单类型", "账单周期", "账单金额", "备注信息", "创建人", "创建时间" };
			// excel文件名
			String fileName = "平台财务账单信息.xls";
			// sheet名
			String sheetName = "财务账单信息信息";
			String[][] values = new String[list.size()][];
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM");
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					FinancialManage obj = list.get(i);
					values[i][0] = obj.getId() == null ? "" : obj.getId();
					if (obj.getBelongPlatform() != null) {
						if (obj.getBelongPlatform() == 1) {
							values[i][1] = "平台本身";
						}
						if (obj.getBelongPlatform() == 1) {
							values[i][1] = "内容平台";
						}
						if (obj.getBelongPlatform() == 1) {
							values[i][1] = "推广平台";
						}
					} else {
						values[i][1] = "";
					}
					values[i][2] = obj.getObjName() == null ? "" : obj.getObjName();
					values[i][3] = obj.getName() == null ? "" : obj.getName();
					if (obj.getType() != null) {
						if (obj.getType() == 1) {
							values[i][4] = "人力成本";
						}
						if (obj.getType() == 2) {
							values[i][4] = "房租";
						}
						if (obj.getType() == 3) {
							values[i][4] = "水电";
						}
						if (obj.getType() == 4) {
							values[i][4] = "业绩";
						}
						if (obj.getType() == 5) {
							values[i][4] = "其它";
						}
					} else {
						values[i][4] = "";
					}
					values[i][5] = obj.getBillCycle() == null ? "" : formatter2.format(obj.getBillCycle());
					values[i][6] = obj.getAmount() == null ? "" : obj.getAmount().toString();
					values[i][7] = obj.getRemark() == null ? "" : obj.getRemark();
					values[i][8] = obj.getCreator() == null ? "" : obj.getCreator();
					values[i][9] = obj.getCreateTime() == null ? "" : formatter.format(obj.getCreateTime());
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 开放平台_KPI列表 导出Excel
	 *
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/KPIToExcel.json")
	@SysLog(module = "KPI目标信息模块", operationDesc = "KPI目标信息导出excel")
	public void KPIToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<FinancialManage> list = new ArrayList<>();
			FinancialManageRequestVO requestVO = this.getParameterBean(FinancialManageRequestVO.class);
			// UserInfo userInfo = this.getCurrentUserInfo(request,UserInfo.class);
			if (requestVO.getType() != null && requestVO.getType() == 2) {
				SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
				if (requestVO.getStartTime() != null) {
					Date end = getLastDayOfMonth(ft.parse(requestVO.getStartTime()));
					requestVO.setEndTime(ft.format(end));
				}
				list = this.financialManageService.financialListToExcel(requestVO.toMap());
			}

			// excel标题
			String[] title = { "编码", "所属平台", "账号信息", "目标周期", "KPI目标值", "备注信息", "创建人", "创建时间" };
			// excel文件名
			String fileName = "平台财务账单信息.xls";
			// sheet名
			String sheetName = "财务账单信息";
			String[][] values = new String[list.size()][];
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM");
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					FinancialManage obj = list.get(i);
					values[i][0] = obj.getId() == null ? "" : obj.getId();
					if (obj.getBelongPlatform() != null) {
						if (obj.getBelongPlatform() == 1) {
							values[i][1] = "平台本身";
						}
						if (obj.getBelongPlatform() == 1) {
							values[i][1] = "内容平台";
						}
						if (obj.getBelongPlatform() == 1) {
							values[i][1] = "推广平台";
						}
					} else {
						values[i][1] = "";
					}
					values[i][2] = obj.getObjName() == null ? "" : obj.getObjName();
					values[i][3] = obj.getBillCycle() == null ? "" : formatter2.format(obj.getBillCycle());
					values[i][4] = obj.getAmount() == null ? "" : obj.getAmount().toString();
					values[i][5] = obj.getRemark() == null ? "" : obj.getRemark();
					values[i][6] = obj.getCreator() == null ? "" : obj.getCreator();
					values[i][7] = obj.getCreateTime() == null ? "" : formatter.format(obj.getCreateTime());
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		// 将文件存到指定位置
		this.setResponseHeader(response, fileName);
		OutputStream os = response.getOutputStream();
		wb.write(os);
		os.flush();
		os.close();
	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}

	/**
	 * 新建账单数据_保存、编辑信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/financialManageSave.json")
	@RequiredParams(names = { "type" })
	public BaseResponseBody financialManageSave(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			FinancialManage financialManage = this.getParameterBean(FinancialManage.class);
			// 测试
			// String finanCiaManageList = this.getParameterString("finanCiaManageList", null);
			// List<FinancialManageRelateAnnex> financialManageRelateAnnexes = JSON.parseArray(finanCiaManageList, FinancialManageRelateAnnex.class);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			List<FinancialManageRelateAnnex> financialManageRelateAnnexList = this.getParameterList("financialManageRelateAnnexList", FinancialManageRelateAnnex.class);
			if (financialManageRelateAnnexList != null && financialManageRelateAnnexList.size() > 0) {
				financialManage.setFinancialManageRelateAnnexList(financialManageRelateAnnexList);
			}
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (financialManage != null && financialManage.getType() != null) {
				if (StringUtils.isNotBlank(financialManage.getId())) {
					this.financialManageService.updateByPrimaryKeySelective(financialManage);
					// 附件逻辑
					if (financialManage.getType() == 1 && financialManageRelateAnnexList != null && financialManageRelateAnnexList.size() > 0) {
						// 库数据
						FinancialManageRelateAnnex financialManageParam = new FinancialManageRelateAnnex();
						financialManageParam.setFinancialManageId(financialManage.getId());
						List<FinancialManageRelateAnnex> relateAnnexList = this.financialManageRelateAnnexService.selectList(financialManageParam);
						// 删除库中
						if (relateAnnexList != null && relateAnnexList.size() > 0) {
							for (FinancialManageRelateAnnex financialManageRelateAnnex : relateAnnexList) {
								this.financialManageRelateAnnexService.deleteByPrimaryKey(financialManageRelateAnnex.getId());
							}
						}
						// 没有就新增
						for (FinancialManageRelateAnnex manageRelateAnnex : financialManageRelateAnnexList) {
							manageRelateAnnex.setFinancialManageId(financialManage.getId());
							this.financialManageRelateAnnexService.insertSelective(manageRelateAnnex);
						}
					}
				} else {
					// 判断相同类型同期账单是否存在
					FinancialManage check = new FinancialManage();
					check.setType(financialManage.getType());
					check.setBillType(financialManage.getBillType());
					check.setStartTime(financialManage.getStartTime());
					check.setEndTime(getLastDayOfMonth(financialManage.getEndTime()));
					check.setObjId(financialManage.getObjId());
					if (financialManage.getType() == null && financialManage.getBillType() == null && financialManage.getStartTime() == null && financialManage.getEndTime() == null && financialManage.getObjId() == null) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.PARAMS_ERROR.getMsg()), null);
					}
					FinancialManage checkFinancialManage = this.financialManageService.checkFinancialManage(check);
					if (checkFinancialManage == null) {
						String primaryKey = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
						financialManage.setId(primaryKey);
						financialManage.setCreator(userInfo.getName());
						financialManage.setCreatorId(userInfo.getId());
						// financialManage.setEndTime(getLastDayOfMonth(financialManage.getStartTime()));
						financialManage.setEndTime(getLastDayOfMonth(financialManage.getEndTime()));
						this.financialManageService.insertSelective(financialManage);
						// 附件凭证信息--财务
						if (financialManage.getType() == 1 && financialManageRelateAnnexList != null && financialManageRelateAnnexList.size() > 0) {
							for (FinancialManageRelateAnnex financialManageRelateAnnex : financialManageRelateAnnexList) {
								financialManageRelateAnnex.setFinancialManageId(primaryKey);
								this.financialManageRelateAnnexService.insertSelective(financialManageRelateAnnex);
							}
						}
					} else {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.FINANCIAL_MANAGE_DATA.getMsg()), null);
					}
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SAVE_SUCCESS.getMsg()), financialManage);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/financialManageDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> financialManageDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.financialManageService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 账单详情信息查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/financialManageInfoById.json")
	@RequiredParams(names = { "id" })
	public BaseResponseBody financialManageInfoById(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			FinancialManage financialManage = this.financialManageService.selectByPrimaryKey(id);
			FinancialManageRelateAnnex relateAnnex = new FinancialManageRelateAnnex();
			relateAnnex.setFinancialManageId(id);
			List<FinancialManageRelateAnnex> financialManageRelateAnnexList = this.financialManageRelateAnnexService.selectList(relateAnnex);
			if (financialManageRelateAnnexList != null && financialManageRelateAnnexList.size() > 0) {
				financialManage.setFinancialManageRelateAnnexList(financialManageRelateAnnexList);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), financialManage);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 根据传入日期获取月最后一天
	 *
	 * @param date
	 * @return
	 */
	private static Date getLastDayOfMonth(final Date date) {
		final Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		final int last = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		cal.set(Calendar.DAY_OF_MONTH, last);
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		return cal.getTime();
	}

}
